package com.maxiaoke.boot.controller;

import com.maxiaoke.boot.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class IndexController {

    /**
     * 跳转到登录页
     *
     * @return
     */
    @GetMapping(value = {"/", "/login"})
    public String loginPage() {
        return "login";
    }

    /**
     * 处理登录请求
     *
     * @return
     */
    @PostMapping("/login")
    public String main(User user, HttpSession session, Model model) {

        if (StringUtils.hasLength(user.getUserName()) && "123456".equals(user.getPassword())) {
            //登录成功的用户保存到session
            session.setAttribute("loginUser", user);
            //登录成功，重定向到main.html页面
            return "redirect:/main.html";
        } else {
            model.addAttribute("msg", "用户名或密码错误");
            return "login";
        }
    }

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 去main页面
     *
     * @return
     */
    @GetMapping("/main.html")
    public String mainPage(HttpSession session, Model model) {

        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        //统计两个页面的访问次数,main.html和dynamic_table
        String mainCount = opsForValue.get("/main.html");
        String dynamiCount = opsForValue.get("/dynamic_table");

        model.addAttribute("mainCount", mainCount);
        model.addAttribute("dynamiCount", dynamiCount);

        return "main";
    }
}
